//
//  NSObject+BaseController.m
//  amigo
//
//  Created by wujian on 2017/8/25.
//  Copyright © 2017年 xiaolian.Inc. All rights reserved.
//

#import "NSObject+BaseController.h"
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import "XLBaseViewController.h"

@implementation NSObject (BaseController)

- (void)setBaseController:(UIViewController *)baseController
{
    objc_setAssociatedObject(self, @selector(baseController), baseController, OBJC_ASSOCIATION_ASSIGN);
}

- (XLBaseViewController *)baseController
{
    if (self == nil || [self isKindOfClass:[NSNull class]]) {
        return nil;
    }
    id curController = objc_getAssociatedObject(self, @selector(baseController));
    if (curController == nil && [self isKindOfClass:[UIResponder class]]) {
        curController = self;
        while (![curController isKindOfClass:[XLBaseViewController class]]) {
            if ([curController nextResponder]) {
                curController = [curController nextResponder];
            }
            else
            {
                curController = nil;
                break;
            }
        }
    }
    return curController;
}


- (UIViewController *)currentTopController
{
    UIViewController *resultVC = [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    while (resultVC.presentedViewController)
    {
        resultVC = [self topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self topViewController:[(UINavigationController *)vc visibleViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [self topViewController:vc.presentedViewController];
        } else {
            return vc;
        }
    }
    return nil;
}

@end
